<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>商品库存余额表</h3>
      <el-button size="small" type="success" @click="handleAdd">
        <i class="el-icon-plus" />
        新增
      </el-button>
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 搜索区域使用 collapse transition -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wapper">
        <div>
          <el-form
            ref="searchForm"
            :model="queryParams"
            :inline="true"
            label-width="90px"
          >
            <el-form-item label="商品名称">
              <el-input
                v-model="queryParams.goodName"
                placeholder="请输入商品名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>

            <el-form-item label="商品类型">
              <el-cascader
                v-model="queryParams.goodType"
                :options="goodsTypeOptions"
                :props="{
                  label: 'name',
                  value: 'id',
                  children: 'list',
                  checkStrictly: true,
                  emitPath: false,
                }"
                clearable
                placeholder="请选择商品类型"
                style="width: 200px"
                @change="handleGoodsTypeChange"
              ></el-cascader>
            </el-form-item>

            <el-form-item label="供应商">
              <el-select
                v-model="queryParams.supplierId"
                placeholder="请选择供应商"
                clearable
                style="width: 200px"
                @change="handleSupplierChange"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="仓库">
              <el-select
                v-model="queryParams.warehouseId"
                placeholder="请选择仓库"
                clearable
                style="width: 200px"
                @change="handleWarehouseChange"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="日期范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                style="width: 350px"
                @change="handleDateChange"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>
    <!-- 操作按钮区域 -->

    <!-- 报表标题 - 居中显示，添加渐变背景 -->
    <!-- <div class="report-title-container">
        <div class="report-title-centered">商品库存余额表</div>
      </div> -->

    <!-- 功能按钮和日期范围 -->
    <div class="report-header">
      <div class="date-range">
        <el-form
          ref="searchForm"
          :model="queryParams"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <el-form-item label="商品名称">
            <el-input
              v-model="queryParams.goodName"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="商品类型">
            <el-cascader
              v-model="queryParams.goodType"
              :options="goodsTypeOptions"
              :props="{
                label: 'name',
                value: 'id',
                children: 'list',
                checkStrictly: true,
                emitPath: false,
              }"
              clearable
              placeholder="请选择商品类型"
              style="width: 200px"
              @change="handleGoodsTypeChange"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="供应商">
            <el-select
              v-model="queryParams.supplierId"
              placeholder="请选择供应商"
              clearable
              style="width: 200px"
              @change="handleSupplierChange"
            >
              <el-option
                v-for="item in supplierOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="仓库">
            <el-select
              v-model="queryParams.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 200px"
              @change="handleWarehouseChange"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 日期: {{ dateRange.start }} 至 {{ dateRange.end }} -->
        <!-- <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
            >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button> -->
        <!-- <el-button
            type="success"
            size="small"
            @click="handleAdd"
            icon="el-icon-plus"
            >新增</el-button
          > -->
        <!-- <el-button
            type="primary"
            size="small"
            icon="el-icon-back"
            @click="goBack"
            >返回</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="handleExport"
            icon="el-icon-download"
            >导出</el-button
          >
          <el-button size="small" @click="handleCheck" icon="el-icon-check"
            >校对库存</el-button
          >
          <el-button size="small" @click="handlePrint" icon="el-icon-printer"
            >打印</el-button
          > -->
      </div>
      <div class="report-actions" />
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="productBalance"
      border
      style="width: 100%"
      :summary-method="getSummaries"
      stripe
    >
      <el-table-column
        label="序号"
        type="index"
        align="center"
        width="80"
        fixed
      />

      <el-table-column
        prop="goodName"
        label="商品名称"
        width="120"
        align="center"
      />

      <el-table-column
        prop="goodsTypeName"
        label="商品类别"
        width="120"
        align="center"
      />

      <el-table-column
        prop="unitName"
        label="单位"
        width="100"
        align="center"
      />

      <el-table-column
        prop="supplierName"
        label="供应商"
        width="120"
        align="center"
      />

      <el-table-column
        prop="warehouseName"
        label="仓库"
        width="120"
        align="center"
      />

      <el-table-column align="center" prop="number" label="数量">
        <template slot-scope="scope">
            {{ scope.row.number || "0" }}
        </template>
      </el-table-column>

      <el-table-column prop="price" label="单价" width="120" align="center">
        <template slot-scope="scope">
          <span :class="{ negative: scope.row.price < 0 }">
            {{ scope.row.price || "0.00" }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="tax" label="税率" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.tax || "0%" }}
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      :title="inventoryForm.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="inventoryForm"
        :model="inventoryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品" prop="goodsId">
          <el-select
            v-model="inventoryForm.goodsId"
            placeholder="请选择商品"
            style="width: 100%"
          >
            <el-option
              v-for="item in goodsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="number">
          <el-input v-model="inventoryForm.number" placeholder="请输入数量" />
        </el-form-item>

        <el-form-item label="仓库" prop="warehouseId">
          <el-select
            v-model="inventoryForm.warehouseId"
            placeholder="请选择仓库"
            style="width: 100%"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 辅助功能侧边栏 -->
    <!-- <div class="side-helper">
        <div class="helper-item" @click="handleRefresh">
          <i class="el-icon-refresh"></i>
        </div>
        <div class="helper-item" @click="handleHelp">
          <i class="el-icon-question"></i>
        </div>
        <div class="helper-item" @click="handleSettings">
          <i class="el-icon-setting"></i>
        </div>
      </div> -->
  </div>
</template>

<script>
import {
  selInventoryListApi,
  addInventoryApi,
  updateInventoryByIdApi,
  delInventoryByIdApi,
} from "@/api/warehouse";
import { selGoodsListApi, selGoodsTypeListApi } from "@/api/goods";
import { selWarehouseListApi, selSupplierListApi } from "@/api/system";

export default {
  name: "InventoryBalanceTableOfGoods",
  data() {
    return {
      isFilterVisible: false, // 控制筛选区域的显示
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        goodType: null, // 使用 goodType 替代 goodsTypeId
        startTime: "", // 开始时间
        endTime: "", // 结束时间
        goodName: "", // 商品名称
        supplierId: "", // 供应商ID
        warehouseId: "", // 仓库ID
      },
      dateRange: [], // 日期范围
      productBalance: [], // 商品库存余额表
      total: 0,
      goodTypeOptions: [], // 商品类别选项
      goodsTypeFilterText: "", // 用于树节点过滤的关键字
      goodsTypeInputName: "", // 显示选中的商品类型名称
      // 查询参数
      goodsQuery: {
        goodsTypeId: null,
        name: "",
        page: 1,
        pageSize: 10,
        supplierId: null,
        warehouseId: null,
      },
      // 仓库列表查询
      warehouseQuery: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      supplierList: [], // 供应商列表
      warehouseList: [], // 仓库列表
      dialogVisible: false,
      // 新增/编辑表单
      inventoryForm: {
        id: "",
        goodsId: "",
        number: "",
        warehouseId: "",
      },
      // 查询参数
      goodsTypeQuery: {
        name: "",
        page: 1,
        pageSize: 10,
        parentId: null,
      },
      goodsTypeOptions: [], // 商品类别列表
      // 供应商查询参数
      supplierQuery: {
        name: "",
        page: 1,
        pageSize: 10,
        supplierTypeId: "",
      },
      supplierOptions: [], // 供应商列表
      rules: {
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        number: [{ required: true, message: "请输入编号", trigger: "blur" }],
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
      },
      goodsList: [],
    };
  },
  created() {
    this.getInventoryList();
    this.selGoodsList();
    this.selWarehouseList();
    this.selGoodsTypeList();
    this.selSupplierList();
  },
  mounted() {
    console.log("初始商品类型options:", this.goodTypeOptions);
    console.log("初始选中值:", this.queryParams.goodType);
  },
  methods: {
    // 获取库存列表
    async getInventoryList() {
      try {
        const res = await selInventoryListApi(this.queryParams);
        this.productBalance = res.records;
        this.total = res.total;
      } catch (error) {
        console.error("获取库存列表失败:", error);
      }
    },
    // 获取商品列表
    async selGoodsList() {
      const res = await selGoodsListApi(this.goodsQuery);
      this.goodsList = res.records || [];
    },
    // 获取供应商列表
    async selSupplierList() {
      const res = await selSupplierListApi(this.supplierQuery);
      this.supplierOptions = res.records;
    },
    // 获取仓库列表
    async selWarehouseList() {
      const res = await selWarehouseListApi(this.warehouseQuery);
      this.warehouseList = res.records || [];
    },
    // 获取商品类别列表
    async selGoodsTypeList() {
      const res = await selGoodsTypeListApi(this.goodsTypeQuery);
      this.goodsTypeOptions = res.records;
      console.log(this.goodsTypeOptions);
      // 如果有预设的商品类型ID，初始化显示名称
      this.initGoodsTypeName();
    },
    // 供应商选择变化处理
    handleSupplierChange(val) {
      this.getInventoryList();
    },
    // 仓库选择变化处理
    handleWarehouseChange(val) {
      this.getInventoryList();
    },
    // 日期范围变化处理
    handleDateChange(val) {
      if (val) {
        // 将毫秒时间戳转换为秒级时间戳
        this.queryParams.startTime = Math.floor(val[0] / 1000);
        this.queryParams.endTime = Math.floor(val[1] / 1000);
        this.getInventoryList();
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
        this.getInventoryList();
      }
    },

    // 搜索按钮点击事件
    handleSearch() {
      this.queryParams.page = 1;
      this.getInventoryList();
    },

    // 重置按钮点击事件
    handleReset() {
      this.dateRange = [];
      this.$refs.searchForm.resetFields();
      this.queryParams = {
        startTime: "",
        endTime: "",
        goodName: "",
        goodType: null,
        supplierId: "",
        warehouseId: "",
        page: 1,
        pageSize: 10,
      };
      this.goodsTypeInputName = "";
      this.getInventoryList();
    },

    handleExport() {
      // 导出功能
      console.log("导出数据");
    },
    handleCheck() {
      // 校对库存
      console.log("校对库存");
    },
    handlePrint() {
      // 打印功能
      console.log("打印");
    },
    handleColumnSettings() {
      // 列设置
      console.log("打开列设置");
    },
    getSummaries(param) {
      // 合计行计算方法
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (
          [
            "baseQuantity",
            "unitCost",
            "totalCost",
            "coldStorageQuantity",
            "foodStorageQuantity",
            "otherStorageQuantity",
          ].includes(column.property)
        ) {
          const values = data.map((item) => Number(item[column.property]));
          sums[index] = values
            .reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0)
            .toFixed(2);
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    goBack() {
      // 返回上一页
      this.$router.go(-1);
    },
    handleRefresh() {
      // 刷新数据
      console.log("刷新数据");
    },
    handleHelp() {
      // 帮助信息
      console.log("显示帮助");
    },
    handleSettings() {
      // 设置
      console.log("打开设置");
    },
    // 格式化时间戳
    formatTimestamp(timestamp) {
      if (!timestamp) return "";
      const date = new Date(timestamp * 1000);
      return this.$moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    // 处理每页显示条数变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getInventoryList();
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getInventoryList();
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true;
      this.inventoryForm = {
        goodsId: "",
        number: "",
        warehouseId: "",
      };
    },
    handleDialogClose() {
      this.$refs.inventoryForm?.resetFields();
      this.inventoryForm = {
        goodsId: "",
        number: "",
        warehouseId: "",
      };
    },
    // 新增/编辑
    handleSubmit() {
      this.$refs.inventoryForm.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            if (this.inventoryForm.id) {
              res = await updateInventoryByIdApi(this.inventoryForm);
            } else {
              const { goodsId, number, warehouseId } = this.inventoryForm;
              res = await addInventoryApi({ goodsId, number, warehouseId });
            }

            if (res.code === 1) {
              this.$message.success(
                this.inventoryForm.id ? "编辑成功" : "新增成功"
              );
              this.dialogVisible = false;
              this.getInventoryList();
            }
          } catch (error) {
            console.error(
              this.inventoryForm.id ? "编辑失败:" : "新增失败:",
              error
            );
            this.$message.error(
              this.inventoryForm.id ? "编辑失败" : "新增失败"
            );
          }
        }
      });
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.inventoryForm = {
        id: row.id,
        goodsId: row.goodsId,
        number: row.number,
        warehouseId: row.warehouseId,
      };
    },
    // 删除
    handleDelete(row) {
      this.$confirm("确认删除该库存记录吗？", "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            // 直接传入id参数
            const res = await delInventoryByIdApi(row.id);
            if (res.code === 1) {
              this.$message.success("删除成功");
              // 删除成功后刷新列表
              this.getInventoryList();
            } else {
              this.$message.error(res.msg || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          // 取消删除操作
          this.$message.info("已取消删除");
        });
    },
    // 格式化Tree数据结构
    formatTreeData(data) {
      return data.map((item) => {
        // 确保list属性存在并处理为children属性
        if (!item.list) {
          item.list = [];
        }
        return item;
      });
    },
    // 初始化时设置已选商品类型的显示名称
    initGoodsTypeName() {
      if (this.queryParams.goodType && this.goodsTypeOptions.length > 0) {
        // 递归查找商品类型名称
        const findTypeName = (data, id) => {
          for (const item of data) {
            if (item.id === this.queryParams.goodType) {
              return item.name;
            }
            if (item.list && item.list.length > 0) {
              const name = findTypeName(item.list, id);
              if (name) return name;
            }
          }
          return null;
        };

        const name = findTypeName(
          this.goodsTypeOptions,
          this.queryParams.goodType
        );
        if (name) {
          this.goodsTypeInputName = name;
        }
      }
    },
    // 筛选节点
    filterGoodsTypeNode(value, data) {
      if (!value) return true;
      return data.name.toLowerCase().indexOf(value.toLowerCase()) !== -1;
    },
    // 处理商品类型变化
    handleGoodsTypeChange(value) {
      console.log("选择的商品类型:", value);
      this.queryParams.goodType = value;
      this.getInventoryList(); // 重新获取库存列表数据
    },
  },
  watch: {
    "queryParams.goodType": {
      handler(val) {
        console.log("商品类型选择变化:", val);
      },
      immediate: true,
    },
    goodsTypeOptions: {
      handler(val) {
        if (val && val.length > 0) {
          this.initGoodsTypeName();
        }
      },
      immediate: true,
    },
    // 监听筛选文本变化
    goodsTypeFilterText(val) {
      if (this.$refs.goodsTypeTree) {
        this.$refs.goodsTypeTree.filter(val);
      }
    },
  },
};
</script>

<style scoped lang="scss">
// 搜索区域样式
.search-wrapper {
  margin-bottom: 15px;
  transition: all 0.3s;
}

.filter-card {
  background-color: #fff;
  border-radius: 4px;
}

.date-range-container {
  display: flex;
  align-items: center;
}

.date-separator {
  margin: 0 5px;
}

.calendar-icon {
  margin-left: 5px;
  color: #909399;
}

.form-buttons {
  margin-left: 10px;
}

// 表格操作区
.table-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.left-operations,
.right-operations {
  display: flex;
  align-items: center;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

// 主内容卡片
.main-content-card {
  background-color: #fff;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

// 报表标题容器 - 添加渐变背景
.report-title-container {
  background: linear-gradient(to right, #f7f9fb, #e8eef5, #f7f9fb);
  padding: 15px 0;
  margin: -40px -20px 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

// 居中显示的报表标题
.report-title-centered {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  position: relative;

  &:after {
    content: "";
    position: absolute;
    bottom: -8px;
    left: 50%;
    transform: translateX(-50%);
    width: 80px;
    height: 3px;
    background: linear-gradient(to right, #f7f9fb, #409eff, #f7f9fb);
    border-radius: 3px;
  }
}

// 功能按钮和日期范围
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.date-range {
  font-size: 14px;
  color: #606266;
}

.report-actions {
  display: flex;
  gap: 10px;
}

// 表格样式
.el-table {
  border-radius: 4px;
  overflow: hidden;

  &::before {
    height: 0;
  }
}

// 数据样式
.product-id {
  color: #409eff;
  font-weight: 500;
}

.product-name {
  font-weight: 500;
}

.quantity {
  font-weight: bold;
  color: #303133;
}

.negative {
  color: #f56c6c;
}

// 辅助功能侧边栏
.side-helper {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background-color: #fff;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
  border-radius: 4px 0 0 4px;
  overflow: hidden;
}

.helper-item {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
  transition: all 0.3s;

  i {
    font-size: 20px;
  }

  &:hover {
    color: #409eff;
    background-color: #ecf5ff;
  }

  &:last-child {
    border-bottom: none;
  }
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.number,
.good-name {
  color: #409eff;
  cursor: pointer;
}
</style>
